<?php
/**
 * Created by PhpStorm.
 * User: davin
 * Date: 14-10-19
 * Time: 下午9:25
 */


class MobileMemberService extends ServiceBase {

    public function createMember($user_info){
        $member = new Member();

        if(count($user_info)<=0){
            $user_info = $this->getDefaultUserInfo();
        }else{
            array_set($user_info, 'email', substr($user_info['username'], 0, 8).'@email.com');
            array_set($user_info, 'password_confirmation', $user_info['password']);
        }

        $member->name = $user_info['username'];
        $member->nick_name = substr($user_info['username'], 0, 8);
        $member->unique_id = $user_info['username'];

        if(!$member->validate()){
            $this->errors()->merge($member->errors());
            return false;
        }

        //create user
        $repo = App::make('UserRepository');
        $user = $repo->signup($user_info);

        if (!$user->id) {
            $this->errors()->merge($user->errors());
            return false;
        }

        //create member
        if(!$member->save()){
            $this->errors()->merge($member->errors());
            return false;
        }
        //relate user and member
        $user->attach_id = $member->id;
        $user->attach_type = 'Member';
        $user->confirmed = 1;
        if(!$user->save()){
            $this->errors()->merge($user->errors());
            return false;
        }

        return true;
    }

    public function getDefaultUserInfo($user_info = array()){
        $user_info = array();
        array_set($user_info, 'username', '91ae9118c51e19907aa8bf55897d290f');
        array_set($user_info, 'email', substr($user_info['username'], 0, 8).'@email.com');
        array_set($user_info, 'password', $this->getAuth('1234'));
        array_set($user_info, 'password_confirmation', $this->getAuth('1234'));
        return $user_info;
    }

    public function getUniqueID(){
        return md5(uniqid(mt_rand(), true));
    }

    public function getAuth($password){
        return substr(sha1($password), 0, 32);
    }


}

